package com.xm.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

@Service
public class ImageCacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String IMAGE_CACHE_PREFIX = "image:";

    public void cacheImage(String imageId, MultipartFile file) throws IOException {
        // 将图片转换为 Base64 字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        file.getInputStream().transferTo(baos);
        String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        
        // 将 Base64 字符串存入 Redis
        redisTemplate.opsForValue().set(IMAGE_CACHE_PREFIX + imageId, base64Image);
    }

    public String getCachedImage(String imageId) {
        // 检查缓存
        String cachedImage = redisTemplate.opsForValue().get(imageId);
        if (cachedImage != null) {
            return cachedImage; // 从缓存中获取
        }

        // 从URL获取图片
        try (InputStream in = new URL(imageId).openStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = out.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            // 存入缓存
            redisTemplate.opsForValue().set(imageId, base64Image);
            return base64Image;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
